<template>
  <div class="roles-page">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button type="primary" @click="isDialogShowFn('add')"
          >添加角色</el-button
        >
      </div>
      <el-table :data="tableData" border style="width: 100%" stripe>
        <el-table-column type="expand">
          <template #default="{ row }">
            <el-row
              v-for="(item1, index) in row.children"
              :key="item1.id"
              :class="['bottom', index === 0 ? 'top' : '']"
            >
              <el-col :span="4">
                <el-tag closable @close="delRolesFn(row, item1.id)">{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="20">
                <el-row
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                  :class="[index2 === 0 ? '' : 'top']"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      type="success"
                      @close="delRolesFn(row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      class="lastTag"
                      @close="delRolesFn(row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" width="50" label="序号">
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="{ row }">
            <!--            @click="handleEdit(scope.$index, scope.row)"-->
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="isDialogShowFn('edit', row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="delFn(row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-menu"
              @click="isDialogShowFn('role', row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      @close="dialogClose"
    >
      <el-tree
        ref="tree"
        v-if="dialogType === 'role'"
        :data="treeList"
        :props="treeProps"
        default-expand-all
        show-checkbox
        node-key="id"
        :default-checked-keys="defKeys"
      ></el-tree>
      <el-form
        v-else
        :model="form"
        label-width="80px"
        :rules="rules"
        ref="form"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="form.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from "element-ui";
import {
  addUserRoleApi,
  delRoleApi,
  delUserApi,
  editRoleApi,
  getRoleTreeApi,
  getUserRoleApi,
  AssignAuthorityApi,
} from "@/api/e-commerce";

export default {
  name: "RolesIndex",
  data() {
    return {
      tableData: [],
      dialogTitle: "",
      dialogFormVisible: false,
      form: {
        roleName: "",
        roleDesc: "",
      },
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称" },
          { min: 2, max: 10, message: "长度在2-10之间" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述" },
          { min: 3, max: 20, message: "长度在3-20之间" },
        ],
      },
      // isDialogShow
      treeList: [],
      treeProps: {
        label: "authName",
        children: "children",
      },
      dialogType: "",
      userInfo: {},
      defKeys: [],
      roleId: [],
    };
  },
  created() {
    this.getUerRoles();
  },
  methods: {
    // 递归函数 获取所有的三级节点
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => this.getLeafKeys(item, arr));
    },
    // 分配权限
    async submit() {
      // console.log(this.dialogType);
      try {
        // 校验表单
        if (this.dialogType === "add") {
          await this.$refs.form.validate();
          const res = await addUserRoleApi(this.form);
          console.log(res);
          this.getUerRoles();
          Message.success("添加成功");
        } else if (this.dialogType === "edit") {
          await this.$refs.form.validate();
          await editRoleApi(this.userInfo.id, this.form);
          this.getUerRoles();
          Message.success("编辑成功");
        } else {
          const keys = [
            ...this.$refs.tree.getCheckedKeys(),
            ...this.$refs.tree.getHalfCheckedKeys(),
          ];
          console.log(keys);
          const idStr = keys.join(",");
          const res = await AssignAuthorityApi(this.roleId, {
            rids: idStr,
          });
          console.log(res);
          console.log(this.roleId);
          Message.success("分配成功");
          this.dialogFormVisible = false;
          this.getUerRoles();
        }
        this.dialogFormVisible = false;
      } catch (err) {
        console.log(err);
        Message.error("添加失败");
      }
      // const res = AssignAuthorityApi()
    },
    // 删除指定权限
    async delRolesFn(row, rid) {
      // console.log(row);
      // console.log(rid);
      try {
        await this.$confirm("此操作将删除该权限, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        const res = await delRoleApi(row.id, rid);
        // console.log(res);
        // 返回的数据直接就是新列表，为了不关闭权限编辑框，直接赋值即可
        row.children = res.data.data;
        Message.success("删除成功");
      } catch (err) {
        Message.info("取消删除");
      }
    },
    // 关闭dialog
    dialogClose() {
      // 清空树形图的key
      this.defKeys = [];
      // 清空form表单的内容
      this.form = {};
      // 这里有问题
      if (this.dialogType !== "role") {
        this.$refs.form.resetFields();
      }
    },
    async getUerRoles() {
      const res = await getUserRoleApi();
      console.log(res);
      this.tableData = res.data.data;
      // console.log(res.data.data);
    },
    async isDialogShowFn(type, userInfo) {
      this.dialogType = type;
      this.dialogFormVisible = true;
      if (type === "add") {
        this.dialogTitle = "添加用户";
      } else if (type === "edit") {
        this.dialogTitle = "修改用户";
        console.log(userInfo);
        this.userInfo = userInfo;
        this.form.roleName = userInfo.roleName;
        this.form.roleDesc = userInfo.roleDesc;
      } else {
        this.roleId = userInfo.id;
        this.dialogTitle = "分配权限";
        const res = await getRoleTreeApi();
        console.log(res);
        this.treeList = res.data.data;
        this.getLeafKeys(userInfo, this.defKeys);
        console.log(this.defKeys);
        console.log(userInfo);
      }
    },
    async delFn(id) {
      console.log(id);
      try {
        await this.$confirm("此操作将删除该用户, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        // 调用删除接口
        const res = await delUserApi(id);
        console.log(res);
        Message.success("删除成功");
        this.getUerRoles();
      } catch (err) {
        Message.info("已取消删除");
        console.log(err);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.roles-page {
  .el-breadcrumb {
    margin-bottom: 15px;
  }
  ::v-deep .el-card__header {
    border-bottom: none;
    padding-bottom: 0;
  }
  .el-row {
    display: flex;
    margin: 10px 0 10px 50px;
    align-items: center;
  }
  .bottom {
    border-bottom: 1px solid #eee;
  }
  .top {
    border-top: 1px solid #eee;
  }
  .lastTag {
    //margin-right: 10px;
    //margin-bottom: 10px;
    margin: 10px;
  }
}
</style>
